/**
 * Copyright &copy; 2012-2016 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package wechat;

import java.security.SecureRandom;
import java.util.UUID;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 封装各种生成唯一性ID算法的工具类.
 * @author ThinkGem
 * @version 2013-01-15
 */
public class IdGen  {
	 private static final long ONE_STEP = 10;
	  private static final Lock LOCK = new ReentrantLock();
	  private static long lastTime = System.currentTimeMillis();
	  private static short lastCount = 0;
	  private static int count = 0;
	
	
	private static SecureRandom random = new SecureRandom();
	
	/**
	 * 封装JDK自带的UUID, 通过Random数字生成, 中间无-分割.
	 */
	public static String uuid() {
		return UUID.randomUUID().toString().replaceAll("-", "");
	}
	
	/**
	 * 使用SecureRandom随机生成Long. 
	 */
	public static long randomLong() {
		return Math.abs(random.nextLong());
	}

	@SuppressWarnings("finally")
	public static String nextId() 
	    {
	        LOCK.lock();
	        try {
	            if (lastCount == ONE_STEP) {
	                boolean done = false;
	                while (!done) {
	                    long now = System.currentTimeMillis();
	                    if (now == lastTime) {
	                        try {
	                            Thread.currentThread();
	                            Thread.sleep(1);
	                        } catch (InterruptedException e) {
	                        }
	                        continue;
	                    } else {
	                        lastTime = now;
	                        lastCount = 0;
	                        done = true;
	                    }
	                }
	            }
	            count = lastCount++;
	        }
	        finally 
	        {
	            LOCK.unlock();
	            return lastTime+""+String.format("%03d",count); 
	        }
	    }

	public static void main(String[] args) {
		System.out.println(nextId());
	}

}
